package com.example.firstapp.adapter;

import android.app.Activity;
import android.content.Context;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.firstapp.R;
import com.example.firstapp.entity.RestaurantReview;

public class ReviewAdapter extends ArrayAdapter<RestaurantReview> {

	private RestaurantReview[] data;
	private int resource;
	private Context context;

	public ReviewAdapter(Context context, int resource, RestaurantReview[] data) {
		super(context, resource, data);
		this.context = context;
		this.resource = resource;
		this.data = data;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View row = convertView;
		ReviewHolder holder = null;

		if (row == null) {
			LayoutInflater inflater = ((Activity) context).getLayoutInflater();
			row = inflater.inflate(resource, parent, false);

			holder = new ReviewHolder();
			holder.author = (TextView) row.findViewById(R.id.review_author);
			holder.date = (TextView) row.findViewById(R.id.review_date);
			holder.content = (TextView) row.findViewById(R.id.review_content);
			holder.rate = (ImageView) row.findViewById(R.id.review_rate);

			row.setTag(holder);
		} else {
			holder = (ReviewHolder) row.getTag();
		}

		RestaurantReview review = data[position];
		holder.author.setText(review.getAuthor());
		holder.date.setText(DateFormat.format("dd-MM-yyyy", review.getDate()));
		holder.content.setText(review.getComment());
		holder.rate.setImageResource(getStarIcon(review.getStar()));

		return row;
	}

	private int getStarIcon(int star) {
		int image;
		switch (star) {
		case 0:
			image = R.drawable.rate_0;
			break;
		case 1:
			image = R.drawable.rate_1;
			break;
		case 2:
			image = R.drawable.rate_2;
			break;
		case 3:
			image = R.drawable.rate_3;
			break;
		case 4:
			image = R.drawable.rate_4;
			break;
		default:
			image = R.drawable.rate_5;
			break;
		}
		return image;
	}

	static class ReviewHolder {
		TextView author;
		TextView date;
		ImageView rate;
		TextView content;
	}
}
